using System.IO;

namespace Bitcoin
{
    static public class Temp_WalletSend
    {
        /// <summary>
        ///     Sends coins to the given address, via the given <see cref="PeerGroupA" />.
        ///     Change is returned to the first key in the wallet.
        /// </summary>
        /// <param name="wallet"></param>
        /// <param name="peerGroup">The peer group to send via.</param>
        /// <param name="to">Which address to send coins to.</param>
        /// <param name="satoshis">How many Satoshis to send. You can use Utils.toNanoCoins() to calculate this.</param>
        /// <returns>
        ///     The <see cref="Transaction" /> that was created or null if there was insufficient balance to send the coins.
        /// </returns>
        /// <exception cref="IOException">If there was a problem broadcasting the transaction.</exception>
        public static Transaction SendCoins(Wallet wallet, PeerGroupA peerGroup, BitcoinAddress to, ulong satoshis)
        {
            lock (wallet)
            {
                var tx = wallet.CreateSend(to, satoshis);
                if (tx == null) // Not enough money! :-(
                    return null;
                if (!peerGroup.BroadcastTransaction(tx))
                {
                    throw new IOException("Failed to broadcast tx to all connected peers");
                }

                // TODO - retry logic
                wallet.ConfirmSend(tx);
                return tx;
            }
        }

        /// <summary>
        ///     Sends coins to the given address, via the given <see cref="PeerA" />.
        ///     Change is returned to the first key in the wallet.
        /// </summary>
        /// <param name="wallet"></param>
        /// <param name="peer">The peer to send via.</param>
        /// <param name="to">Which address to send coins to.</param>
        /// <param name="satoshis">How many Satoshis to send. You can use Utils.ToNanoCoins() to calculate this.</param>
        /// <returns>The <see cref="Transaction" /> that was created or null if there was insufficient balance to send the coins.</returns>
        /// <exception cref="IOException">If there was a problem broadcasting the transaction.</exception>
        public static Transaction SendCoins(Wallet wallet, PeerA peer, BitcoinAddress to, ulong satoshis)
        {
            lock (wallet)
            {
                var tx = wallet.CreateSend(to, satoshis);
                if (tx == null) // Not enough money! :-(
                    return null;
                peer.BroadcastTransaction(tx);
                wallet.ConfirmSend(tx);
                return tx;
            }
        }
    }
}